package com.ruoyi.generateTest.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.generateTest.domain.GenerateTestPaper;
import com.ruoyi.generateTest.domain.GeneratedExam;
import com.ruoyi.generateTest.utils.GenerateQuestionsUtil;
import com.ruoyi.generateTest.utils.ModifyDocFormatUtil;
import com.ruoyi.generateTest.utils.WordToExcelUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.generateTest.domain.TestPaper;
import com.ruoyi.generateTest.service.ITestPaperService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.generateTest.utils.WordToExcelUtil.wordToExcelGeneral;


/**
 * 试题Controller
 *
 * @author 经纬线
 * @date 2024-07-10
 */
@RestController
@RequestMapping("/generateTest/test_paper")
public class TestPaperController extends BaseController {
    @Autowired
    private ITestPaperService testPaperService;

    /**
     * 查询试题列表
     */
    @PreAuthorize("@ss.hasPermi('list')")
    @GetMapping("/list")
    public TableDataInfo list(TestPaper testPaper) {
        startPage();
        List<TestPaper> list = testPaperService.selectTestPaperList(testPaper);
        return getDataTable(list);
    }

    /**
     * 导出试题列表
     */
    @PreAuthorize("@ss.hasPermi('export')")
    @Log(title = "试题", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TestPaper testPaper) {


        List<TestPaper> list = testPaperService.selectTestPaperList(testPaper);
        System.out.println(list);

        System.out.println("9999999999999999999" + profile);
        ExcelUtil<TestPaper> util = new ExcelUtil<TestPaper>(TestPaper.class);
        util.exportExcel(response, list, "试题数据");
    }


    /**
     * 获取试题详细信息
     */
    @PreAuthorize("@ss.hasPermi('query')")
    @GetMapping(value = "/{testId}")
    public AjaxResult getInfo(@PathVariable("testId") Long testId) {
        return success(testPaperService.selectTestPaperByTestId(testId));
    }

    /**
     * 新增试题
     */
    @PreAuthorize("@ss.hasPermi('add')")
    @Log(title = "试题", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TestPaper testPaper) {
        return toAjax(testPaperService.insertTestPaper(testPaper));
    }

    /**
     * 修改试题
     */
    @PreAuthorize("@ss.hasPermi('edit')")
    @Log(title = "试题", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TestPaper testPaper) {
        return toAjax(testPaperService.updateTestPaper(testPaper));
    }

    /**
     * 删除试题
     */
    @PreAuthorize("@ss.hasPermi('remove')")
    @Log(title = "试题", businessType = BusinessType.DELETE)
    @DeleteMapping("/{testIds}")
    public AjaxResult remove(@PathVariable Long[] testIds) {
        return toAjax(testPaperService.deleteTestPaperByTestIds(testIds));
    }


    /**
     * word上传路径
     */
    private static String profile;

    @Value("${ruoyi.profile}")
    public void setFilePath(String path) {
        profile = path;
    }


    /**
     * 获取word文件路径
     *
     * @param testId word试题Id
     * @return word文件路径
     */
    @PreAuthorize("@ss.hasPermi('WordToExcel')")
    @Log(title = "word转excel试题下载", businessType = BusinessType.EXPORT)
    @GetMapping(value = "/word-to-excel/{testId}")
    public String getWordPath(@PathVariable("testId") Long testId) {
        TestPaper testPaper = testPaperService.selectTestPaperByTestId(testId);
        return profile + testPaper
                .getTestFile()
                .replaceAll("^/profile", "");
    }


    /**
     * word转excel下载链接
     *
     * @param testId word试题Id
     * @return excel文件流
     * @throws IOException io异常
     */
    @Anonymous
    @GetMapping("/word-to-excel/download/{testId}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable("testId") Long testId) throws IOException {
        File file = new File(getWordPath(testId));  // 根据testId返回word所在路径
        byte[] data = wordToExcelGeneral(file, 1);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=converted_file.xlsx");

//        System.out.println(Arrays.toString(data));
        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }

    private String savePath = "C:\\考试系统项目\\修改格式文档\\修改格式后_" + System.currentTimeMillis() + ".docx";


    /**
     * 修改文档格式
     * @param modify_document_form 修改文档格式表单数据
     * @return  修改后的文档流
     * @throws Exception python脚本执行异常
     */
    @Anonymous
    @ResponseBody
    @PostMapping(value = "/modify_document", produces = {"application/json;charset=utf-8"})
    public ResponseEntity<byte[]> modify_document(@RequestBody Map<String, Object> modify_document_form) throws Exception {
        // 获取生成试题源文件路径
        TestPaper testPaper = testPaperService
                .selectTestPaperByTestId(((Integer) modify_document_form.get("modify_document_fileId"))
                        .longValue());
        File file = new File(profile + testPaper
                .getTestFile()
                .replaceAll("^/profile", ""));

        // 调用修改文档格式方法
        ModifyDocFormatUtil.ModifyDocFormat(
                file.toString(),
                savePath,
                "22",
                String.valueOf(modify_document_form.get("fontName")),
                String.valueOf(modify_document_form.get("chineseFontName")),
                String.valueOf(modify_document_form.get("fontSize")),
                String.valueOf(modify_document_form.get("lineSpacing")),
                String.valueOf(modify_document_form.get("lineSpacingRule")),
                String.valueOf(modify_document_form.get("firstLineIndentChars")),
                String.valueOf(modify_document_form.get("headingFontName")),
                String.valueOf(modify_document_form.get("headingChineseFontName")),
                String.valueOf(modify_document_form.get("headingFontSize")),
                String.valueOf(modify_document_form.get("headingLineSpacing")),
                String.valueOf(modify_document_form.get("headingLineSpacingRule")),
                String.valueOf(modify_document_form.get("headingFirstLineIndentChars")),
                Integer.parseInt(String.valueOf(modify_document_form.get("autoPageBreak"))),
                Integer.parseInt(String.valueOf(modify_document_form.get("centerHeading")))

        );

        // 读取保存后，修改的文档流
        File modify_file = new File(savePath);
        byte[] data = Files.readAllBytes(modify_file.toPath());
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=document.docx");
        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }


    /**
     * 一键修改文档（python脚本固定参数）
     * @param testId 试题Id
     * @return 修改后的文档流
     * @throws Exception python脚本执行异常
     */
    @Anonymous
    @ResponseBody
    @GetMapping(value = "/modify_document_template/{testId}", produces = {"application/json;charset=utf-8"})
    public ResponseEntity<byte[]> modify_document_template(@PathVariable("testId") Long testId) throws Exception {
        // 获取生成试题源文件路径
        File file = new File(getWordPath(testId));
        // 调用模板（固定参数）修改文档格式方法
        ModifyDocFormatUtil.ModifyDocFormatTemplate(file.toString(), savePath);
        // 读取保存后，修改的文档流
        File modify_file = new File(savePath);
        byte[] data = Files.readAllBytes(modify_file.toPath());
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=document.docx");
        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }

}
